//using Gateway.Logger;
using Gateway.OpenTelemetry;
using Gateway.UI.Api;
using Microsoft.Extensions.FileProviders;
using Serilog;
//using NLog.Extensions.Logging;

var builder = WebApplication.CreateBuilder(args);

//apollo
// builder.Configuration.AddApollo();
{
    var environment = builder.Environment;
    string name = environment.EnvironmentName.ToLower();
    string fileTmpPrefix = "";
    if (string.IsNullOrEmpty(name))
    {
        fileTmpPrefix = ".prod";
    }
    else
    {
        fileTmpPrefix = $".{name}";
    }

    InitializeJsonFile(fileTmpPrefix);

    builder.Configuration.AddJsonFile($"appsettings{fileTmpPrefix}.json");
}
//builder.Logging.AddNLog();
// config opentelemetry
{
    //builder.ConfigureOpenTelemetry();
}
{
    builder.AddServiceDefaults();
    //Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(builder.Configuration).CreateLogger();

    //var loggerFactory = LoggerFactory.Create(builder =>
    //{
    //    builder.ClearProviders();
    //    builder.AddSerilog();
    //});
    //使用Serilog
    builder.Host.UseSerilog((context, logger) =>
    {
        //Serilog读取配置
        logger.ReadFrom.Configuration(context.Configuration);
        logger.Enrich.FromLogContext();
        logger.Enrich.WithThreadId();
         logger.Enrich.WithThreadName();
        logger.Enrich.WithMachineName();
    });


}

builder.Services.AddResponseCompression();

builder.Services.AddMvcCore().AddApiExplorer();

builder.Services.ReplaceConfiguration(builder.Configuration);
builder.WebHost.ConfigureKestrel((context, options) =>
{
    options.Limits.MaxRequestBodySize = 100 * 1024 * 1024;
});


await builder.Services.AddApplicationAsync<StartupModule>();
var app = builder.Build();
// add wwwroot page html 
{
    app.Use((async (context, next) =>
    {
        if (context.Request.Path == "/")
        {
            context.Request.Path = "/index.html";
        }

        context.Response.Headers["Gateway-Versions"] = "1.0.0.1";
        context.Response.Headers["Gateway-Name"] = "Gateway";

        await next(context);

        if (context.Response.StatusCode == 404)
        {
            context.Request.Path = "/index.html";
            await next(context);
        }
    }));

    var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }
    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(path),
    });
}
app.UseResponseCompression();

await app.InitializeApplicationAsync();
await app.RunAsync();


// 初始化配置文件
void InitializeJsonFile(string env)
{
    string settingDir = "appsettings";
    // 加载根目录的配置文件
    {
        var settingsPath = new DirectoryInfo(Path.Combine(AppContext.BaseDirectory, "appsettings"));
        if (settingsPath.Exists)
        {
            FileInfo[] files = settingsPath.GetFiles($"*.json", SearchOption.TopDirectoryOnly);
            foreach (FileInfo fileInfo in files)
            {
                builder.Configuration.AddJsonFile(fileInfo.FullName, optional: true, reloadOnChange: true);
                Console.WriteLine("加载配置文件:" + fileInfo.Name);
            }
        }
    }


    // 加载缓存配置文件
    {
        var directory = new DirectoryInfo(Path.Combine(AppContext.BaseDirectory, settingDir, "cache"));
        if (directory.Exists)
        {
            FileInfo[] files = directory.GetFiles($"*.json", SearchOption.TopDirectoryOnly);
            foreach (FileInfo fileInfo in files)
            {
                builder.Configuration.AddJsonFile(fileInfo.FullName, optional: true, reloadOnChange: true);
                Console.WriteLine("加载Cache配置文件:" + fileInfo.Name);
            }
        }

        var redisDirectory =
            new DirectoryInfo(Path.Combine(AppContext.BaseDirectory, settingDir, "cache", "redisConfigs"));
        if (redisDirectory.Exists)
        {
            FileInfo[] files = redisDirectory.GetFiles($"*{env}.json", SearchOption.TopDirectoryOnly);
            foreach (FileInfo fileInfo in files)
            {
                builder.Configuration.AddJsonFile(fileInfo.FullName, optional: true, reloadOnChange: true);
                Console.WriteLine("加载redis配置文件:" + fileInfo.Name);
            }
        }
    }

    // 加载http配置文件
    {
        var directory =
            new DirectoryInfo(Path.Combine(AppContext.BaseDirectory, settingDir, "http"));
        if (directory.Exists)
        {
            FileInfo[] files = directory.GetFiles($"*{env}.json", SearchOption.TopDirectoryOnly);
            foreach (FileInfo fileInfo in files)
            {
                builder.Configuration.AddJsonFile(fileInfo.FullName, optional: true, reloadOnChange: true);
                Console.WriteLine("加载Http配置文件:" + fileInfo.Name);
            }
        }
    }
    // 加载api url 配置文件
    {
        var directory =
            new DirectoryInfo(Path.Combine(AppContext.BaseDirectory, settingDir, "apis"));
        if (directory.Exists)
        {
            FileInfo[] files = directory.GetFiles($"*{env}.json", SearchOption.TopDirectoryOnly);
            foreach (FileInfo fileInfo in files)
            {
                builder.Configuration.AddJsonFile(fileInfo.FullName, optional: true, reloadOnChange: true);
                Console.WriteLine("加载api url配置文件:" + fileInfo.Name);
            }
        }
    }

    // 加载ai 配置文件
    {
        var directory =
            new DirectoryInfo(Path.Combine(AppContext.BaseDirectory, settingDir, "AI"));
        if (directory.Exists)
        {
            FileInfo[] files = directory.GetFiles($"*{env}.json", SearchOption.TopDirectoryOnly);
            foreach (FileInfo fileInfo in files)
            {
                builder.Configuration.AddJsonFile(fileInfo.FullName, optional: true, reloadOnChange: true);
                Console.WriteLine("加载AI配置文件:" + fileInfo.Name);
            }
        }
    }
}